// pages2/pages/index/sleepDetection/index.js
import subPub from '../../../../utils/subPub';
import * as echarts from '../../components/ec-canvas/echarts';
const $api = require('../../../../request/api').API;
const app = getApp();
/**
 * 获取yyyy-MM-dd这样格式的日期数组
 * @param {number} beforeMonths 多少个月之前
 */
function getDates(beforeMonths) {
  const arr = [];
  let date = new Date();
  let stamp = date.getTime();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  arr.push({
    date: `${year}-${month}-${day}`
  });
  for (let i = 1; i <= beforeMonths; i++) {
    stamp;
  }
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    navIndex: 0,
    navList: [{ name: '实体报告' }, { name: '睡眠报告' }, { name: '使用报告' }],
    dateClassifyList: [{ name: '日' }, { name: '周' }, { name: '月' }, { name: '季' }, { name: '年' }],
    datePickerList: [],
    breatheChart: {
      lazyLoad: true
    },
    heartChart: {
      lazyLoad: true
    },
    online: false, // true表示在线 false表示离线
    // heartRateException:"", // 心率是否异常
    // respiratoryRateException:"", // 呼吸率是否异常
    heartRateMinute: 0, // 每分钟的心率
    respiratoryReteMinute: 0, // 每分钟的呼吸率
    loading: true,
    stateName: '无 人',
    respiratoryRateName: '正常',
    heartRateName: '正常',
    equipMac: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ state, id, equipMac }) {
    this.setData({
      online: state == 2 ? true : false,
      id,
      equipMac
    });
    // this.getData("30558a891d09")
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const { online, equipMac } = this.data;
    if (online) {
      const breatheOption = this.getBreatheOption(this.getBreaRateList({ category: '', data: '' }, 1));
      const rateOption = this.getRateOption(this.getBreaRateList({ category: '', data: '' }, 2));
      this.renderEchart('#breathe-rate', breatheOption).then(res => (this.chart1 = res));
      this.renderEchart('#heart-rate', rateOption).then(res => (this.chart2 = res));
    }
    // 监听数据在线
    this.sleepSyncDetectionPushId = subPub.on('sleepSyncDetectionPush', data => {
      console.log('监听到数据在线', data);
      const { heartRate, respiratoryRate, timeS, timeM, timeH, deviceId, bodyStatus } = data;
      if (deviceId !== equipMac) return;
      this.getData(deviceId);
      const category = [timeH, timeM, timeS].join(':');
      const breatheOption = this.getBreatheOption(this.getBreaRateList({ category, data: respiratoryRate }, 1));
      const rateOption = this.getRateOption(this.getBreaRateList({ category, data: heartRate }, 2));
      if (!this.data.online) {
        this.setData(
          {
            online: true
          },
          () => {
            // 等页面显示完成
            this.renderEchart('#breathe-rate', breatheOption).then(res => (this.chart1 = res));
            this.renderEchart('#heart-rate', rateOption).then(res => (this.chart2 = res));
          }
        );
      } else {
        if (this.chart1) {
          this.chart1.setOption(breatheOption);
        } else {
          this.renderEchart('#breathe-rate', breatheOption).then(res => (this.chart1 = res));
        }
        if (this.chart2) {
          this.chart2.setOption(rateOption);
        } else {
          this.renderEchart('#heart-rate', rateOption).then(res => (this.chart2 = res));
        }
      }
      wx.hideLoading();
      this.setData({
        loading: false,
        stateName: this.formatBodyStatus(bodyStatus),
        respiratoryRateName: this.formatRespiratoryRate(respiratoryRate, data),
        heartRateName: this.formatHeartRate(heartRate, data),
        respiratoryReteMinute: respiratoryRate,
        heartRateMinute: heartRate
      });
    });
    this.deviceOnlineId = subPub.on('deviceOnline', deviceId => {
      console.log('监听到数据在线');
      if (deviceId !== equipMac) return;
      wx.hideLoading();
      this.setData({
        online: true,
        loading: false
      });
    });
    // 监听设备离线
    this.deviceOfflineId = subPub.on('deviceOffline', deviceId => {
      console.log('监听到数据离线');
      if (deviceId !== equipMac) return;
      wx.hideLoading();
      this.setData({
        online: false,
        loading: false
      });
    });
  },
  async getData(deviceId) {
    if (this.alreadyGet) return;
    const res = await $api.getByDeviceId(deviceId);
    this.alreadyGet = true;
    console.log(res);
  },
  /**
   * @param {number} type type为1表示呼吸数据，type为2表示心跳数据
   */
  getBreaRateList(data, type) {
    this.respiratoryRateList = this.respiratoryRateList || [];
    this.heartRateList = this.heartRateList || [];
    const arr = type == 1 ? this.respiratoryRateList : this.heartRateList;
    if (!arr.length) {
      do {
        arr.push({
          category: '',
          data: ''
        });
      } while (arr.length < 6);
    }
    const targetIndex = arr.findIndex(item => !item.category);
    if (targetIndex != -1) {
      arr.splice(targetIndex, 1, data);
    } else {
      arr.shift();
      arr.push(data);
    }
    return {
      category: arr.map(item => item.category),
      data: arr.map(item => item.data)
    };
  },
  formatBodyStatus(type) {
    switch (type) {
      case 0:
        return '无 人';
      case 1:
        return '静 息';
      case 2:
        return '安 静';
      case 3:
        return '动 作';
      case 4:
        return '持 续 动 作';
    }
  },
  formatRespiratoryRate(respiratoryRate, { respiratoryRateMax, respiratoryRateMin, bodyStatus }) {
    if ((respiratoryRate >= respiratoryRateMin && heartRate <= respiratoryRateMax) || !bodyStatus) {
      return '正常';
    } else if (respiratoryRate < respiratoryRateMin) {
      return '偏低';
    } else if (respiratoryRate > respiratoryRateMax) {
      return '偏高';
    }
  },
  formatHeartRate(heartRate, { heartRateMax, heartRateMin, bodyStatus }) {
    if ((heartRate >= heartRateMin && heartRate <= heartRateMax) || !bodyStatus) {
      return '正常';
    } else if (heartRate < heartRateMin) {
      return '偏低';
    } else if (heartRate > heartRateMax) {
      return '偏高';
    }
  },
  clickNav(e) {
    const { item } = e.target.dataset;
    if (item === undefined) return;
    this.setData({
      navIndex: item
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  /**
   *@param selector 选择器
   *@param option echart的option
   */
  renderEchart(selector, option) {
    return new Promise((resolve, _) => {
      this.selectComponent(selector).init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });

        chart.setOption(option);
        resolve(chart);
        return chart;
      });
    });
  },
  // 获取呼吸率选项
  getBreatheOption({ category, data }) {
    const max = Math.max(data);
    return {
      animation: false,
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: {
          //坐标轴刻度标签的相关设置。
          interval: 0
        },
        data: category
      },
      yAxis: {
        type: 'value',
        min: 0,
        interval: 10,
        max: max > 40 ? null : 40
      },
      series: [
        {
          type: 'line',
          itemStyle: {
            normal: {
              label: { show: true } //顶部显示数值
            }
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(58,77,233,0.8)'
              },
              {
                offset: 1,
                color: 'rgba(58,77,233,0.3)'
              }
            ])
          },
          data
        }
      ]
    };
  },
  // 获取心率选项
  getRateOption({ category, data }) {
    const max = Math.max(data);
    return {
      animation: false,
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: {
          //坐标轴刻度标签的相关设置。
          interval: 0
        },
        data: category
      },
      yAxis: {
        type: 'value',
        min: 0,
        interval: 30,
        max: max > 150 ? null : 150
      },
      series: [
        {
          type: 'line',
          itemStyle: {
            normal: {
              label: { show: true } //顶部显示数值
            }
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(140,23,235,0.8)'
              },
              {
                offset: 1,
                color: 'rgba(177,130,215,0.3)'
              }
            ])
          },
          data
        }
      ]
    };
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    subPub.off('sleepSyncDetectionPush', this.sleepSyncDetectionPushId);
    subPub.off('deviceOffline', this.deviceOfflineId);
    subPub.off('deviceOnline', this.deviceOnlineId);
    // app.globalData.socket.removeListener("sleepSyncDetectionPush")
    // app.globalData.socket.removeListener("deviceOffline")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
